package com.liaoyin.travel.util;

import com.liaoyin.travel.constant.CommonParamter;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;

public class QiniuUtil {
	
	// 密钥配置
	private static Auth auth;
	// 创建上传对象
	UploadManager uploadManager = new UploadManager();

	// 简单上传，使用默认策略，只需要设置上传的空间名就可以了
	public static String getUpToken(String type) {
		if(auth == null) {
			getAuthThread();
		}
		if("1".equals(type)) {			
			return auth.uploadToken(CommonParamter.picture);
		}else {
			return auth.uploadToken(CommonParamter.video);
		}
	}
	
	public static Auth getAuthThread() {		
		auth = Auth.create(CommonParamter.ACCESS_KEY, CommonParamter.SECRET_KEY);
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return auth;
	}
	

	public String upload(MultipartFile file) throws IOException {
		try {
			String key = UUIDUtil.getUUID();
			// 获取文件名称
			String fileName = file.getOriginalFilename();
			// 文件名称后的类型
			String extensionName = fileName
					.substring(fileName.lastIndexOf("."));
			key += extensionName;
			// 调用put方法上传
			Response res = uploadManager
					.put(file.getBytes(), key, getUpToken("1"));
			// 打印返回的信息
			System.out.println(res.bodyString());
			return key;
		} catch (QiniuException e) {
			Response r = e.response;
			// 请求失败时打印的异常的信息
			System.out.println(r.bodyString());			
		}
		return null;
	}
	
	public String download(String url){
		return auth.privateDownloadUrl(url);
	}
	
	public static void main(String[] args) {
		 QiniuUtil q= new QiniuUtil();
		 System.out.println(getUpToken("1"));
	}

}
